import requests
import json
import time
from datetime import datetime, date, timedelta

# 配置
BASE_URL = "http://127.0.0.1:5000"

class HealthAPITester:
    def __init__(self, base_url):
        self.base_url = base_url
        self.token = None
        self.user_id = None
        self.test_data = {}
    
    def print_separator(self, title):
        print(f"\n{'='*60}")
        print(f" 🏥 {title} ")
        print(f"{'='*60}")
    
    def print_request_info(self, method, endpoint, data=None):
        print(f"\n📤 {method} {endpoint}")
        if data:
            print(f"📦 请求数据: {json.dumps(data, ensure_ascii=False, indent=2)}")
    
    def print_response_info(self, response):
        print(f"📥 响应状态码: {response.status_code}")
        try:
            response_data = response.json()
            print(f"✅ 响应数据: {json.dumps(response_data, ensure_ascii=False, indent=2)}")
            return response_data
        except:
            print(f"❌ 响应内容: {response.text}")
            return None
    
    def setup_auth(self):
        """设置认证信息"""
        self.print_separator("用户认证设置")
        
        # 注册新用户
        username = f"health_test_{int(time.time())}"
        user_data = {
            "username": username,
            "email": f"{username}@example.com",
            "password": "123456",
            "full_name": "健康测试用户",
            "age": 30,
            "gender": "male",
            "height": 175.0,
            "weight": 70.0
        }
        
        response = requests.post(f"{self.base_url}/api/auth/register", json=user_data)
        if response.status_code == 201:
            data = response.json()
            self.token = data['access_token']
            self.user_id = data['user']['id']
            print(f"✅ 用户注册成功 - ID: {self.user_id}")
            return True
        else:
            print("❌ 用户注册失败，尝试登录...")
            # 尝试登录
            login_data = {
                "username": "health_test_123",
                "password": "123456"
            }
            response = requests.post(f"{self.base_url}/api/auth/login", json=login_data)
            if response.status_code == 200:
                data = response.json()
                self.token = data['access_token']
                self.user_id = data['user']['id']
                print(f"✅ 用户登录成功 - ID: {self.user_id}")
                return True
            return False
    
    def get_headers(self):
        """获取请求头"""
        return {"Authorization": f"Bearer {self.token}"}
    
    def test_vital_signs(self):
        """测试生命体征接口"""
        self.print_separator("1. 生命体征接口测试")
        
        # 1.1 创建生命体征记录
        print("\n--- 1.1 创建生命体征记录 ---")
        vital_data = {
            "heart_rate": 75,              # 整数 - 心率
            "blood_pressure_systolic": 120, # 整数 - 收缩压
            "blood_pressure_diastolic": 80, # 整数 - 舒张压
            "respiratory_rate": 16,        # 整数 - 呼吸频率
            "blood_oxygen": 98.5,          # 浮点数 - 血氧饱和度
            "body_temperature": 36.8       # 浮点数 - 体温
        }
        
        self.print_request_info("POST", "/api/vital-signs", vital_data)
        response = requests.post(
            f"{self.base_url}/api/vital-signs", 
            json=vital_data, 
            headers=self.get_headers()
        )
        response_data = self.print_response_info(response)
        
        if response.status_code == 201:
            record_id = response_data['data']['id']
            self.test_data['vital_signs_id'] = record_id
            print(f"✅ 创建成功 - 记录ID: {record_id}")
            
            # 1.2 更新生命体征记录
            print("\n--- 1.2 更新生命体征记录 ---")
            update_data = {
                "heart_rate": 78,
                "blood_oxygen": 99.0
            }
            self.print_request_info("PUT", f"/api/vital-signs/{record_id}", update_data)
            response = requests.put(
                f"{self.base_url}/api/vital-signs/{record_id}", 
                json=update_data, 
                headers=self.get_headers()
            )
            self.print_response_info(response)
            
            # 1.3 查询生命体征记录
            print("\n--- 1.3 查询生命体征记录 ---")
            self.print_request_info("GET", f"/api/vital-signs/{record_id}")
            response = requests.get(
                f"{self.base_url}/api/vital-signs/{record_id}", 
                headers=self.get_headers()
            )
            self.print_response_info(response)
            
            # 1.4 删除生命体征记录
            print("\n--- 1.4 删除生命体征记录 ---")
            self.print_request_info("DELETE", f"/api/vital-signs/{record_id}")
            response = requests.delete(
                f"{self.base_url}/api/vital-signs/{record_id}", 
                headers=self.get_headers()
            )
            self.print_response_info(response)
            
            return True
        return False
    
    def test_body_composition(self):
        """测试身体成分接口"""
        self.print_separator("2. 身体成分接口测试")
        
        # 2.1 创建身体成分记录
        print("\n--- 2.1 创建身体成分记录 ---")
        body_data = {
            "weight": 72.5,                # 浮点数 - 体重
            "body_fat_percentage": 18.5,   # 浮点数 - 体脂率
            "muscle_mass": 55.0,           # 浮点数 - 肌肉量
            "water_percentage": 60.2,      # 浮点数 - 水分率
            "waist_circumference": 85.0,   # 浮点数 - 腰围
            "hip_circumference": 95.0      # 浮点数 - 臀围
        }
        
        self.print_request_info("POST", "/api/body-composition", body_data)
        response = requests.post(
            f"{self.base_url}/api/body-composition", 
            json=body_data, 
            headers=self.get_headers()
        )
        response_data = self.print_response_info(response)
        
        if response.status_code == 201:
            record_id = response_data['data']['id']
            self.test_data['body_composition_id'] = record_id
            print(f"✅ 创建成功 - 记录ID: {record_id}")
            
            # 2.2 更新身体成分记录
            print("\n--- 2.2 更新身体成分记录 ---")
            update_data = {
                "weight": 71.8,
                "body_fat_percentage": 18.2
            }
            self.print_request_info("PUT", f"/api/body-composition/{record_id}", update_data)
            response = requests.put(
                f"{self.base_url}/api/body-composition/{record_id}", 
                json=update_data, 
                headers=self.get_headers()
            )
            self.print_response_info(response)
            
            # 2.3 查询身体成分记录
            print("\n--- 2.3 查询身体成分记录 ---")
            self.print_request_info("GET", f"/api/body-composition/{record_id}")
            response = requests.get(
                f"{self.base_url}/api/body-composition/{record_id}", 
                headers=self.get_headers()
            )
            self.print_response_info(response)
            
            # 2.4 删除身体成分记录
            print("\n--- 2.4 删除身体成分记录 ---")
            self.print_request_info("DELETE", f"/api/body-composition/{record_id}")
            response = requests.delete(
                f"{self.base_url}/api/body-composition/{record_id}", 
                headers=self.get_headers()
            )
            self.print_response_info(response)
            
            return True
        return False
    
    def test_blood_test(self):
        """测试血液检测接口"""
        self.print_separator("3. 血液检测接口测试")
        
        # 3.1 创建血液检测记录
        print("\n--- 3.1 创建血液检测记录 ---")
        blood_data = {
            "fasting_blood_sugar": 5.2,        # 浮点数 - 空腹血糖
            "postprandial_blood_sugar": 6.8,   # 浮点数 - 餐后血糖
            "hba1c": 5.5,                      # 浮点数 - 糖化血红蛋白
            "total_cholesterol": 4.8,          # 浮点数 - 总胆固醇
            "triglycerides": 1.2,              # 浮点数 - 甘油三酯
            "hdl_cholesterol": 1.3,            # 浮点数 - 高密度脂蛋白
            "ldl_cholesterol": 2.8,            # 浮点数 - 低密度脂蛋白
            "alt": 25.0,                       # 浮点数 - 谷丙转氨酶
            "ast": 22.0                        # 浮点数 - 谷草转氨酶
        }
        
        self.print_request_info("POST", "/api/blood-test", blood_data)
        response = requests.post(
            f"{self.base_url}/api/blood-test", 
            json=blood_data, 
            headers=self.get_headers()
        )
        response_data = self.print_response_info(response)
        
        if response.status_code == 201:
            record_id = response_data['data']['id']
            self.test_data['blood_test_id'] = record_id
            print(f"✅ 创建成功 - 记录ID: {record_id}")
            
            # 3.2 更新血液检测记录
            print("\n--- 3.2 更新血液检测记录 ---")
            update_data = {
                "fasting_blood_sugar": 5.4,
                "hdl_cholesterol": 1.4
            }
            self.print_request_info("PUT", f"/api/blood-test/{record_id}", update_data)
            response = requests.put(
                f"{self.base_url}/api/blood-test/{record_id}", 
                json=update_data, 
                headers=self.get_headers()
            )
            self.print_response_info(response)
            
            # 3.3 查询血液检测记录
            print("\n--- 3.3 查询血液检测记录 ---")
            self.print_request_info("GET", f"/api/blood-test/{record_id}")
            response = requests.get(
                f"{self.base_url}/api/blood-test/{record_id}", 
                headers=self.get_headers()
            )
            self.print_response_info(response)
            
            # 3.4 删除血液检测记录
            print("\n--- 3.4 删除血液检测记录 ---")
            self.print_request_info("DELETE", f"/api/blood-test/{record_id}")
            response = requests.delete(
                f"{self.base_url}/api/blood-test/{record_id}", 
                headers=self.get_headers()
            )
            self.print_response_info(response)
            
            return True
        return False
    
    def test_daily_activity(self):
        """测试日常活动接口"""
        self.print_separator("4. 日常活动接口测试")
        
        # 4.1 创建日常活动记录
        print("\n--- 4.1 创建日常活动记录 ---")
        today = date.today().isoformat()
        activity_data = {
            "record_date": today,           # 字符串 - 日期 (YYYY-MM-DD)
            "steps": 8520,                  # 整数 - 步数
            "exercise_minutes": 45,         # 整数 - 运动时长
            "calories_burned": 320.5,       # 浮点数 - 消耗卡路里
            "sleep_hours": 7.5,             # 浮点数 - 睡眠时长
            "sleep_quality": "good",        # 字符串 - 睡眠质量
            "water_intake": 2.1,            # 浮点数 - 饮水量
            "notes": "今日完成45分钟有氧运动" # 字符串 - 备注
        }
        
        self.print_request_info("POST", "/api/daily-activity", activity_data)
        response = requests.post(
            f"{self.base_url}/api/daily-activity", 
            json=activity_data, 
            headers=self.get_headers()
        )
        response_data = self.print_response_info(response)
        
        if response.status_code == 201:
            record_id = response_data['data']['id']
            self.test_data['daily_activity_id'] = record_id
            print(f"✅ 创建成功 - 记录ID: {record_id}")
            
            # 4.2 更新日常活动记录
            print("\n--- 4.2 更新日常活动记录 ---")
            update_data = {
                "steps": 9200,
                "sleep_hours": 8.0,
                "notes": "更新：晚上多走了几步"
            }
            self.print_request_info("PUT", f"/api/daily-activity/{record_id}", update_data)
            response = requests.put(
                f"{self.base_url}/api/daily-activity/{record_id}", 
                json=update_data, 
                headers=self.get_headers()
            )
            self.print_response_info(response)
            
            # 4.3 查询日常活动记录
            print("\n--- 4.3 查询日常活动记录 ---")
            self.print_request_info("GET", f"/api/daily-activity/{record_id}")
            response = requests.get(
                f"{self.base_url}/api/daily-activity/{record_id}", 
                headers=self.get_headers()
            )
            self.print_response_info(response)
            
            # 4.4 删除日常活动记录
            print("\n--- 4.4 删除日常活动记录 ---")
            self.print_request_info("DELETE", f"/api/daily-activity/{record_id}")
            response = requests.delete(
                f"{self.base_url}/api/daily-activity/{record_id}", 
                headers=self.get_headers()
            )
            self.print_response_info(response)
            
            return True
        return False
    
    def test_health_assessment(self):
        """测试健康评估接口"""
        self.print_separator("5. 健康评估接口测试")
        
        # 5.1 创建健康评估记录
        print("\n--- 5.1 创建健康评估记录 ---")
        next_checkup = (date.today() + timedelta(days=90)).isoformat()
        assessment_data = {
            "overall_health_score": 85,         # 整数 - 健康评分
            "health_risk_level": "low",         # 字符串 - 风险等级
            "bmi_category": "normal",           # 字符串 - BMI分类
            "cardiovascular_risk": "low",       # 字符串 - 心血管风险
            "diabetes_risk": "low",             # 字符串 - 糖尿病风险
            "metabolic_risk": "low",            # 字符串 - 代谢风险
            "recommendations": "继续保持健康生活方式，定期监测血压和血糖", # 字符串 - 建议
            "next_checkup_date": next_checkup   # 字符串 - 下次检查日期
        }
        
        self.print_request_info("POST", "/api/health-assessment", assessment_data)
        response = requests.post(
            f"{self.base_url}/api/health-assessment", 
            json=assessment_data, 
            headers=self.get_headers()
        )
        response_data = self.print_response_info(response)
        
        if response.status_code == 201:
            record_id = response_data['data']['id']
            self.test_data['health_assessment_id'] = record_id
            print(f"✅ 创建成功 - 记录ID: {record_id}")
            
            # 5.2 更新健康评估记录
            print("\n--- 5.2 更新健康评估记录 ---")
            update_data = {
                "overall_health_score": 88,
                "recommendations": "更新建议：增加有氧运动频率"
            }
            self.print_request_info("PUT", f"/api/health-assessment/{record_id}", update_data)
            response = requests.put(
                f"{self.base_url}/api/health-assessment/{record_id}", 
                json=update_data, 
                headers=self.get_headers()
            )
            self.print_response_info(response)
            
            # 5.3 查询健康评估记录
            print("\n--- 5.3 查询健康评估记录 ---")
            self.print_request_info("GET", f"/api/health-assessment/{record_id}")
            response = requests.get(
                f"{self.base_url}/api/health-assessment/{record_id}", 
                headers=self.get_headers()
            )
            self.print_response_info(response)
            
            # 5.4 删除健康评估记录
            print("\n--- 5.4 删除健康评估记录 ---")
            self.print_request_info("DELETE", f"/api/health-assessment/{record_id}")
            response = requests.delete(
                f"{self.base_url}/api/health-assessment/{record_id}", 
                headers=self.get_headers()
            )
            self.print_response_info(response)
            
            return True
        return False
    
    def run_all_tests(self):
        """运行所有测试"""
        print("🚀 开始健康检测系统API全面测试")
        
        if not self.setup_auth():
            print("❌ 认证失败，无法继续测试")
            return
        
        tests = [
            self.test_vital_signs,
            self.test_body_composition,
            self.test_blood_test,
            self.test_daily_activity,
            self.test_health_assessment
        ]
        
        passed_tests = 0
        total_tests = len(tests)
        
        for test in tests:
            try:
                if test():
                    passed_tests += 1
                    print(f"✅ {test.__name__} 测试通过")
                else:
                    print(f"❌ {test.__name__} 测试失败")
            except Exception as e:
                print(f"💥 {test.__name__} 测试异常: {e}")
        
        # 测试总结
        self.print_separator("测试总结")
        print(f"📊 总测试模块: {total_tests}")
        print(f"✅ 通过: {passed_tests}")
        print(f"❌ 失败: {total_tests - passed_tests}")
        print(f"📈 通过率: {passed_tests/total_tests*100:.1f}%")
        
        if passed_tests == total_tests:
            print("🎉 所有健康模型接口测试通过！")
        else:
            print("💡 部分测试失败，请检查接口实现")

if __name__ == "__main__":
    tester = HealthAPITester(BASE_URL)
    tester.run_all_tests()